﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Brjostagjof_H4.Models;
using System.Web.Util;

using System.Collections;
using System.Web.Security;

namespace Brjostagjof_H4.Controllers
{
    [HandleError]
    public class AdminController : Controller
    {
        IMonsterRepository monster = null;

        [Authorize(Roles = "Administrators")]
        public ActionResult EditThisUser(string userName)
        {
            if (userName != "")
            {
                UserHandling u = monster.getUserEditByUserName(userName);

                return View(u);
            }

            return RedirectToAction("NotFound", "Home");
        }

        [Authorize(Roles = "Administrators")]
        [HttpPost]
        public ActionResult EditThisUser(UserHandling user)
        {
            string chosenRole = Request.Form["Roles"];
            bool isUserActive = bool.Parse( Request.Form["Active"].ToString() );

            monster.updateBan(user.UserName, isUserActive);

            if (user != null)
            {
                // Prevents duplicates
                if (Roles.IsUserInRole(user.UserName, "Administrators"))
                    Roles.RemoveUserFromRole(user.UserName, "Administrators");

                if (Roles.IsUserInRole(user.UserName, "Professionals"))
                    Roles.RemoveUserFromRole(user.UserName, "Professionals");
                // ends

                if (chosenRole != "Parents")
                {
                    Roles.AddUserToRole(user.UserName, chosenRole);

                    if (Roles.IsUserInRole(user.UserName, chosenRole))
                        return RedirectToAction("EditUser");
                    else
                        return RedirectToAction("Error", "Shared");
                }
            }

            if (chosenRole == "Parents") // If selected role is Parents then nothing is done
                return RedirectToAction("EditUser");

            else
                return RedirectToAction("NotFound", "Shared");
        }



        [Authorize(Roles = "Administrators")]
        public ActionResult EditUser()
        {
            return View(monster.getUserEditList());
        }

        public AdminController()
        {
            monster = new MonsterRepository();
        }

        public AdminController(IMonsterRepository inRep)
        {
            monster = inRep;
        }

        public  IEnumerable<entryType> entryTypes = new List<entryType> 
        { 
            new entryType {
               typeID = 1,
               name = "Grein"
            },
            new entryType {
                typeID = 2,
                name = "Frétt"
            }
        };
        
        [Authorize(Roles = "Administrators")]
        [HttpGet]
        public ActionResult EditCategories()
        {
            List<Category> model = monster.getCategories();

            if (model != null)
                return View(model);
            else
                return View(); // Setja NotFound eða eitthvað - VB
        }

        [Authorize(Roles = "Administrators")]
        [HttpPost]
        public ActionResult EditCategories(FormCollection formData)
        {
            List<Category> c = monster.getCategories();

            if (c != null)
            {
                UpdateModel(c);
                monster.updateCategories(c);

                return RedirectToAction("EditCategories");
            }
            else
            {
                return View("EditCategories"); // Breyta í eitthvað error message
            }
        }

        [Authorize(Roles = "Administrators")]
        [HttpGet]
        public ActionResult EditDonate()
        {
            About model = monster.getDonate();

            if (model != null)
                return View(model);
            else
                return View();
        }

        [Authorize(Roles = "Administrators")]
        [HttpPost]
        public ActionResult EditDonate(FormCollection formData)
        {
            About a = monster.getDonate();

            if (a != null)
            {
                UpdateModel(a);
                monster.updateDonate(a, User.Identity.Name);

                return RedirectToAction("EditDonate");
            }
            else
            {
                return RedirectToAction("Error", "Shared"); // Breyta
            }
        }

        [Authorize(Roles = "Administrators")]
        [HttpGet]
        public ActionResult EditPharmacist()
        {
            About model = monster.getPharmacist();

            if (model != null)
                return View(model);
            else
                return View();
        }

        [Authorize(Roles = "Administrators")]
        [HttpPost]
        public ActionResult EditPharmacist(FormCollection formData)
        {
            About a = monster.getPharmacist();

            if (a != null)
            {
                UpdateModel(a);
                monster.updatePharmacist(a, User.Identity.Name);

                return RedirectToAction("EditPharmacist");
            }
            else
            {
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult About()
        {
            /*v ar a = monster.getAbout();
            var result = HttpUtility.HtmlDecode(a.content);

            a.content = result; 
             */

            return View(monster.getAbout());
        }

        [Authorize(Roles = "Administrators")]
        
        [HttpGet]
        public ActionResult EditAbout()
        {
            About model = monster.getAbout();

            if (model != null)
                return View(model);
            else
                return View();
        }

        [Authorize(Roles = "Administrators")]
        [HttpPost]
        public ActionResult EditAbout(FormCollection formData)
        {
            About a = monster.getAbout();

            if (a != null)
            {
                UpdateModel(a);
                monster.updateAbout(a, User.Identity.Name);

                return RedirectToAction("EditAbout");
            }
            else
            {
                return RedirectToAction("Error", "Shared"); // Breyta
            }
        }

        /// <summary>
        /// View existing entries, which ones depending on your role.
        /// </summary>
        /// <returns>List of entries.</returns>
        [Authorize(Roles="Professionals, Administrators")]
        public ActionResult Entries()
        {
            var entryList = new List<Entry>();
            // Checking what role the user is in 
            if (User.IsInRole("Administrators")) 
            {
                entryList = monster.getXLatestEntries(20); // List all entries
            }
            else // Then the user must be a Professional and can only see his own entries
            {
                // Look up his identity and reference with the database
                String strUser = User.Identity.Name;
                var profile = monster.getProfileByUserName(strUser);
                var userId = profile.UserId;
                entryList = monster.getXLatestEntriesByID(20, userId); // List all entries by this user
            }
            // Put the entries into the model to be given to the view.
            List<EntryListModel> entryListModelList = new List<EntryListModel>();
            foreach (var e in entryList)
            {
                EntryListModel entryListModel = new EntryListModel();
                entryListModel.ID = e.ID;
                entryListModel.posted = e.posted.ToString();
                entryListModel.title = e.title;
                entryListModel.author = monster.getUserNameByID(e.added_by);

                var theEntryType = e.entry_type;
                var myType = entryTypes.Where(x => x.typeID == theEntryType).SingleOrDefault().name;
                entryListModel.type = myType;

                entryListModelList.Add(entryListModel);
            }
            return View(entryListModelList);
        }

        [Authorize(Roles = "Professionals, Administrators")]
        public ActionResult CreateEntry()
        {
            return View();
        }

        [Authorize(Roles = "Professionals, Administrators")]
        [HttpPost]
        public ActionResult CreateEntry(EntryModel model)
        {
            if (ModelState.IsValid)
            {
                String strUser = User.Identity.Name; // Getting the username from session
                var result = monster.getProfileByUserName(strUser); // Fetching the user's profile
                model.userId = result.UserId; // Putting the profile's userId into the EntryModel
                
                monster.addEntry(model);
                return RedirectToAction("Entries", "Admin");
            }
            return View(model);
        }

        [Authorize(Roles = "Professionals, Administrators")]
        public ActionResult EditEntry(int? id)
        {
            if (id.HasValue)
            {
                int realId = id.Value;

                Entry entry = monster.getEntryById(realId);
                if (entry != null)
                {
                    // Move the Entry to EntryModel
                    EntryModel entryModel = new EntryModel();
                    entryModel.title = entry.title;
                    entryModel.content = entry.content;
                    entryModel.category = entry.category;
                    entryModel.entry_type = entry.entry_type;
                    entryModel.entry_status = entry.entry_status;
                    return View(entryModel);
                }
            }
            return View("Error");
        }

        /// <summary>
        /// HttpPost for editing entry.
        /// </summary>
        /// <param name="entryModel">The EntryModel being edited.</param>
        /// <returns>Redirect to the entries overview action.</returns>
        [Authorize(Roles = "Professionals, Administrators")]
        [HttpPost]
        public ActionResult EditEntry(EntryModel entryModel)
        {
            if (ModelState.IsValid)
            {
                Entry entry = new Entry();
                entry.title = entryModel.title;
                entry.content = entryModel.content;
                entry.category = entryModel.category;
                entry.entry_type = entryModel.entry_type;
                entry.entry_status = entryModel.entry_status;
                entry.ID = entryModel.id;
                monster.updateEntry(entry);
                return RedirectToAction("Entries", "Admin");
            }
            return View(entryModel);
        }
    }
}
